<template>
  <el-drawer v-model="drawer" title="章节编辑"
    size="800"
    @closed="handleClose"
  >
    <el-form ref="refChapterForm"
      :model="store.chapter"
      :rules="rules"
      label-width="120px"
      style="width: 90%"
      v-if="store.chapter"
    >
      <el-form-item label="课程" prop="lesson">
        <el-input v-model="store.chapter.lesson" disabled />
      </el-form-item>
      <el-form-item label="章节名称" prop="title">
        <el-input v-model="store.chapter.title" placeholder="请填写章节名称" />
      </el-form-item>
      <el-form-item label="视频地址" prop="video">
        <el-input v-model="store.chapter.video" placeholder="请填写视频地址" />
      </el-form-item>
      <el-form-item label="视频时长" prop="duration">
        <el-input v-model="store.chapter.duration" placeholder="请填写视频时长" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useChapterStore } from '@/stores/chapter';

const drawer = ref(false)
const store = useChapterStore()
const router = useRouter()
const route = useRoute()
const refChapterForm = ref()
const rules = {
  title: [{required: true, message: '未填写章节名称', trigger: 'blur'}],
  video: [{required: true, message: '未填写视频地址', trigger: 'blur'}],
  duration: [{required: true, message: '未填写视频时长', trigger: 'blur'}]
}

const handleClose = () => {
  drawer.value = false
  router.back()
}
const handleSave = () => {
  refChapterForm.value.validate(async(valid: boolean) => {
    if (valid) {
      const result = await store.saveChapter()
      if (result) {
        store.loadChapters(parseInt(route.params.lessonId as string))
        ElMessage.success('保存成功')
        router.back()
      }
    }
  })
}

onMounted(async() => {
  drawer.value = true
  if (route.params.lessonId) {
    await store.loadLesson(parseInt(route.params.lessonId as string))
  }
  if (route.params.id) {
    await store.loadChapter(parseInt(route.params.id as string))
  } else {
    await store.newChapter()
  }
})
</script>